<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车-青鸟优品</title>
    <link rel="stylesheet" href="./assets/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="./assets/css/common.css">
    <link rel="stylesheet" href="./assets/css/cart.css">
    <script src="./assets/js/jquery.js"></script>
    <script src="./assets/bootstrap/js/bootstrap.min.js"></script>
    <script src="./assets/js/common.js"></script>
    <script src="./assets/layer/layer.js"></script>
    <style>
        .btn-del,
        .del-all-checked {
            cursor: pointer;
        }
    </style>
    <!-- 
        商品素材来自京东
        https://new.jd.com/?innerAnchor=100011386594_100012254352_100006378137_100011529848&focus=1 
    -->
</head>

<body>

    <nav class="navbar navbar-fixed-top">
        <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="./index.html">青鸟商城</a>
            </div>

            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav navbar-left">
                    <!-- <li class="active"><a href="./list.html">热门推荐 <span class="sr-only">(current)</span></a></li>
                    <li><a href="#">国际品牌</a></li>
                    <li><a href="#">数码电器</a></li>
                    <li><a href="#">每日特价</a></li> -->
                </ul>

                <ul class="nav navbar-nav navbar-right">
                    <li><a href="./login.html">登录</a></li>
                    <li><a href="./reg.html">注册</a></li>
                </ul>

            </div>
        </div>
    </nav>

    <div class="container cart">

        <div class="row table-responsive" style="background-color: #FFF;">
            <table class="table">
                <thead>
                    <tr>
                        <td>
                            <label>
                                <input type="checkbox" class="all-checkbox"> 全选
                            </label>
                        </td>
                        <td>商品</td>
                        <td>单价</td>
                        <td>数量</td>
                        <td>小计</td>
                        <td>操作</td>
                    </tr>
                </thead>
                <tbody>
                    <!-- 购物车商品列表 -->
                </tbody>

                <tfoot>
                    <tr>
                        <td colspan="3">
                            <div class="checkbox">
                                <label>
                                    <input type="checkbox" class="all-checkbox" />
                                    全选
                                </label>
                                &nbsp;&nbsp;
                                <span class="text-muted del-all-checked">删除选中商品</span>
                            </div>
                        </td>
                        <td colspan="3" align="right">
                            <b class="total">总价: &yen; 00.00</b>
                            <button class="btn btn-lg btn-danger btn-order">去结算</button>
                        </td>
                    </tr>
                </tfoot>
            </table>
        </div>

    </div>


    <div class="container-fluid footer">
        <div class="row">
            <div class="col-lg-12">
                Copyright 2019 by www.braccp.com 北京畅想唯优信息技术有限公司 All rights reserved.
            </div>
        </div>
        <div class="row">
            <div class="col-lg-12">
                联系电话：029-88212666 地址：西安市雁塔区电子一路 石油大学北门工会楼二层
            </div>
        </div>

        <div class="row">
            <div class="col-lg-12">
                备案号：陕ICP备19013769号-1
            </div>
        </div>
    </div>

    <div class="fixed-nav-right">
        <!-- 返回首页 -->
        <div class="fixed-home">
            <a href="./index.html">
                <i class="glyphicon glyphicon-home"></i>
            </a>
        </div>
        <!-- 购物车 -->
        <div class="fixed-cart">
            <a href="./cart.html">
                <i class="glyphicon glyphicon-shopping-cart"></i>
            </a>
        </div>
        <!-- 返回顶部 -->
        <div class="back-top">
            <i class="glyphicon glyphicon-chevron-up"></i>
        </div>
    </div>


</body>
<script>
    $(function () {
        // 从本地存储中读取购物车信息
        var cart = JSON.parse(localStorage.getItem('cart') || '[]');
        // console.log(cart);
        var html = '';
        cart.forEach(item => {
            // 判断当前商品是否需要勾选
            if(item.checked&&item.checked===1){
                var checked='checked';
            }else{
                var checked='';
            }
            html += `
            <tr class="cart-item">
                    <td>
                        <input type="checkbox" ${checked} class="item-checkbox" pid="${item.id}">
                    </td>
                    <td>

                        <div class="media">
                            <div class="media-left">
                                <a href="#">
                                    <img src="${item.cover}" alt="">
                                </a>
                            </div>
                            <div class="media-body">
                                ${item.name}
                            </div>
                        </div>

                    </td>
                    <td>
                        <span class="price">&yen;${item.price}</span>
                    </td>
                    <td>
                        <div class="input-group product-count">
                            <div pid="${item.id}" class="input-group-addon btn-reduce">-</div>
                            <input type="text" style="padding:0;text-align:center" class="form-control" value="${item.num}">
                            <div pid="${item.id}" class="input-group-addon btn-add">+</div>
                        </div>
                    </td>

                    <td>
                        <span class="price">&yen;${item.price * item.num}</span>
                    </td>
                    <td>
                        <a class="text-muted btn-del" pid="${item.id}">删除</a>
                    </td>
                </tr>

            `;
            // 渲染页面
            $("tbody").html(html);
            // 更新商品总价
            updateTotal();

        });

        // 更新购物车商品的数量
        $(".btn-add").on('click', function () {
            var input = $(this).siblings('input');
            var num = parseInt(input.val()) + 1;
            if (num <= 10) {
                input.val(num);
            } else {
                return layer.msg('库存不足');
            }
            // 获取商品id
            var pid = $(this).attr('pid');
            // 查找商品对象在购物车中的索引
            var index = cart.findIndex((item) => item.id === pid);
            // 更新商品数量
            cart[index].num = num;
            console.log(cart);
            // 更新购物车
            localStorage.setItem('cart', JSON.stringify(cart));
            // 更新商品总价
            updateTotal();
            // 更新小计
            var price = num * cart[index].price;
            $(this).parents('td').next('td').children('.price').html(`&yen; ${price}`);

        });
        $(".btn-reduce").on('click', function () {
            var input = $(this).siblings('input');
            var num = parseInt(input.val()) - 1;
            if (num > 0) {
                input.val(num);
            } else {
                return layer.msg('商品数量不能小于1');
            }
            // 获取商品id
            var pid = $(this).attr('pid');
            // 查找商品对象在购物车中的索引
            var index = cart.findIndex((item) => item.id === pid);
            // 更新商品数量
            cart[index].num = num;
            // 更新购物车
            localStorage.setItem('cart', JSON.stringify(cart));
            // 更新商品总价
            updateTotal();
            // 更新小计
            var price = num * cart[index].price;
            $(this).parents('td').next('td').children('.price').html(`&yen; ${price}`);
        });

        // 删除购物车中的商品
        $(".btn-del").on('click', function () {
            if (!confirm('确认删除?')) {
                return false;
            }
            // 获取商品id
            var pid = $(this).attr('pid');
            var index = cart.findIndex(item => item.id == pid);
            cart.splice(index, 1);
            // 移除页面的dom结构
            $(this).parents('tr').remove();
            // 更新商品总价
            updateTotal();
            // 更新购物车
            localStorage.setItem('cart', JSON.stringify(cart));
        });
        // 全选反选
        $(".all-checkbox").on('click', function () {
            var status = $(this).prop('checked');
            $(".item-checkbox").prop('checked', status);
            $(".all-checkbox").prop('checked', status);
        });
        $(".item-checkbox").on('click', function () {
            // 所有商品的复选框
            var len = $(".item-checkbox").length;
            // 已经勾选的复选框
            var checkedLen = $(".item-checkbox:checked").length;
            if (checkedLen === len) {
                $(".all-checkbox").prop('checked', true);
            } else {
                $(".all-checkbox").prop('checked', false);
            }
        });

        // 删除选中商品
        $(".del-all-checked").on('click', function () {
            if (!confirm('确认删除?')) {
                return false;
            }
            var items = $(".item-checkbox:checked");
            // // 移除对应的tr
            items.each((index, item) => {
                // 移除dom结构
                $(item).parents('tr').remove();
                // 获取商品id
                var pid = $(item).attr('pid');
                var index = cart.findIndex(item => item.id == pid);
                cart.splice(index, 1);
                // 更新购物车
                localStorage.setItem('cart', JSON.stringify(cart));
                //  更新购物车总价
                updateTotal();
            });

        });

        $(".btn-order").on('click',function(){
            // 判断用户是否勾选了商品
            var items = $(".item-checkbox:checked");
            if(items.length===0){
                return layer.msg('请勾选要购买的商品');
            }
            // 通过商品id去购物车中查找商品信息
            var cart=JSON.parse(localStorage.getItem('cart')||'[]');
            items.each((index,item)=>{
                // 通过自定义属性获取商品id
                var pid=$(item).attr('pid');
                // 获取当前商品在购物车中的索引
                var index=cart.findIndex(val=>val.id===pid);
                // 更新购物车信息
                cart[index].checked=1;
            });
            // 更新购物车信息
            localStorage.setItem('cart',JSON.stringify(cart));
            // 跳转到结算页面
            location.href='/order.html';
        });

        // 计算商品总价
        function updateTotal() {
            var total = 0;
            cart.forEach(item => {
                total += parseFloat(item.price * item.num);
            });
            $(".total").html(`总价: &yen; ${total}`);
        }
    });
</script>

</html>